/*
 * @Description:
 * @Author: Chetwyn
 * @Date: 2019-08-30 11:21:11
 * @LastEditors: lhtack
 * @LastEditTime: 2019-09-27 13:26:05
 */
import React, { PureComponent } from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  TouchableWithoutFeedback,
  StyleSheet,
  Platform,
  StatusBar,
  ScrollView,
  TextInput,
  Image,
  Animated,
  LayoutAnimation,
  FlatList,
} from 'react-native';
import { SafeAreaView } from 'react-navigation';
import { get, map, toNumber } from 'lodash';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { LoadingProgramModule } from 'react-native-cgws-support';

import { fetchData, toggleErrorInfo, toggleOverlayContainer } from '../actions';
import { getColors } from '../theme';
import { SafeView, DialogAlert } from '../component';
import PropTypes from 'prop-types';
import {
  api,
  SortTypeEnum,
  RiskLevelEnum,
  DirectionTypeEnum,
  RelationTypeEnum,
  CustomerLevelEnum,
  FavorEnum,
  ActiveEnum,
  RelationType,
  RelationTypeName,
  OverViewType
} from '../constants';
import {
  ic_selection,
  ic_down_a,
  ic_down_n,
  ic_screen,
  ic_follow_a,
  ic_follow_n,
  ic_message,
  ic_short_message,
  ic_telephone,
  ic_cannot_find,
  ic_search,
  ic_clear,
  ic_tips,
  ic_selection_blue
} from '../assets';
import {
  VerifyDataUtils,
  LinkingUtils,
  RNJumpUtils,
  scaleSizeW,
  scaleSizeH,
  scaleSizeFont,
} from '../utils';

// componentDidMount
// xiong 处理tab 切换及filter点击事件
_onFilterPress = () => {
  this.setState((preState) => ({
    showFilterList: !preState.showFilterList,
  }));
};

// xiong  第二种方法
const FilterButtons = ({ onChange, name }) => {
  console.log('111-111-111>>>> ', onChange, name);
  return (
    <TouchableOpacity
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        alignItems: 'center',
      }}
      onPress={() => {
        console.log('点击筛选看看每次都会打印么！！！！');
        onChange && onChange('FILTER');
      }}
    >
      <View
        style={{
          height: scaleSizeH(26),
          justifyContent: 'center',
        }}
      >
        <Text
          style={{
            fontSize: scaleSizeFont(15),
            color: getColors().base_fc_6,
          }}
        >
          {name}
        </Text>
      </View>
      <Image
        style={{
          marginLeft: scaleSizeW(5),
          resizeMode: 'contain',
        }}
        source={ic_screen}
      />
    </TouchableOpacity>
  );
};

// 默认筛选条件
const defaultFilterParams = {
  total: {
    max: undefined,
    min: undefined,
  },
  stock: {
    max: undefined,
    min: undefined,
  },
  fund: {
    max: undefined,
    min: undefined,
  },
  margin: {
    max: undefined,
    min: undefined,
  },
  marketValueTotal: {  // 总市值
    max: undefined,
    min: undefined,
  },
  customerLevel: '',   // 客户等级
  isStore: '',         // 是否激活
  relationType: '',    // 关系类型
  riskLevel: '',       // 风险等级
  isActive: '',
};

// xiong
const services = [
  {
    name: '周转率',
    type: RelationType.turnoverRate,
  },
  {
    name: '月佣金贡献',
    type: RelationType.myjby,
  },
  {
    name: '季佣金贡献',
    type: RelationType.myjj3y,
  }
];
// xiong
const Separator = () => (
  <View
    style={{
      alignSelf: 'stretch',
      height: 1,
      backgroundColor: getColors().base_lc_1,
    }}
  />
);
// xiong
const Services = ({ onPress, onClose, selectedRelationType }) => (
  <View style={{ backgroundColor: getColors().base_oc_11 }}>
    {map(services, (item, index) => {
      const isSelected = selectedRelationType === item.type;
      const color = isSelected ? getColors().base_oc_25 : getColors().base_oc_7;
      const source = isSelected ? ic_selection_blue : undefined;

      return [
        <TouchableOpacity
          key={index + ''}
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            height: scaleSizeH(45),
            paddingHorizontal: scaleSizeW(20),
            backgroundColor: getColors().base_oc_11,
          }}
          onPress={() => {
            console.log('这里可以点击么？', isSelected, item.type)
            if (isSelected) {
              onClose && onClose();
            } else {
              onPress && onPress(item.type);
            }
          }}
        >
          <View
            style={{
              height: scaleSizeH(40),
              justifyContent: 'center',
              // backgroundColor: '#cccccc',
              // width: '100%'
            }}
          >
            <Text
              style={{
                fontSize: scaleSizeFont(15),
                color
              }}
            >
              {item.name}
            </Text>
          </View>
          <Image
            style={{
              marginLeft: scaleSizeW(5),
              resizeMode: 'contain',
              height: scaleSizeH(14),
              width: scaleSizeW(14),
            }}
            source={source}
          />
        </TouchableOpacity>,
        <Separator key={2 * index + 1 + ''} visible={index !== 2} />,
      ];
    })}
  </View>
);

// xiong 点击弹出层
const FilterPanel = (props) => {
  console.log('d-----', props)
  const {
    visible,
    selectedRelationType,
    onRelationTypeSelect,
    onClose,
  } = props;

  return visible ? (
    <View
      style={{
        zIndex: 8888888,
        backgroundColor: '#00000066',
        position: 'absolute',
        top: scaleSizeH(44),
        left: 0,
        right: 0,
        bottom: 0,
      }}
    >

      <Services
        selectedRelationType={selectedRelationType}
        onPress={onRelationTypeSelect}
        onClose={onClose}
      />

      <TouchableOpacity
        style={{ flex: 1, alignSelf: 'stretch' }}
        onPress={onClose}
      />

    </View >
  ) : null;
};

const RequestTypes = {
  load: 'load', // 获取第一页
  page: 'page', // 获取下一页
  refresh: 'refresh', // 刷新
};

class SelectItem extends PureComponent {
  static propTypes = {
    id: PropTypes.string.isRequired,
    activeId: PropTypes.string,
    onPress: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
  }
  componentDidMount() { }
  render() {
    let { id, activeId, onPress } = this.props;
    let isSelected = id === activeId;

    return (
      <TouchableOpacity
        style={{
          width: scaleSizeW(77),
          height: scaleSizeH(28),
          ...this.props.style,
        }}
        onPress={() => {
          onPress && onPress();
        }}
      >
        <View
          style={{
            backgroundColor: isSelected
              ? getColors().base_oc_11
              : getColors().base_oc_28,
            borderRadius: 2,
            borderColor: isSelected ? getColors().base_oc_27 : 'transparent',
            borderWidth: isSelected ? 1 : 0,
            flex: 1,
            alignSelf: 'stretch',
            justifyContent: 'center',
            alignItems: 'center',
          }}
        >
          <Text style={{ color: getColors().base_fc_5, fontSize: 15 }}>
            {this.props.children}
          </Text>
          {isSelected && (
            <View
              style={{
                borderTopWidth: 10,
                borderTopColor: '#004ECC',
                borderLeftWidth: 10,
                borderLeftColor: 'transparent',
                borderRightWidth: 10,
                borderRightColor: 'transparent',
                borderBottomWidth: 10,
                borderBottomColor: 'transparent',
                position: 'absolute',
                right: -10,
                bottom: -10,
                transform: [{ rotate: '-45deg' }],
              }}
            />
          )}
          {isSelected && (
            <Image
              source={ic_selection}
              style={{ position: 'absolute', right: -2, bottom: 0 }}
            />
          )}
        </View>
      </TouchableOpacity>
    );
  }
}

const TopFilter = props => {
  const { sortList, sortBy, sortDirection, onSorterPress, showRelationPanel,
    selectedRelationType, onRelationBtnPress, onRelationTypeSelect } = props;
  // console.log('xiong 看看这是啥sortList', sortList) // 四个数据
  // console.log('xiong 看看这是啥sortBy', sortBy)   // EDFAULT
  // console.log('xiong 看看这是啥sortDirection', sortDirection)  // DESC
  // console.log('xiong 看看这是啥onSorterPress', onSorterPress)   // 一个函数
  // console.log('xiong 看看这是啥onRelationBtnPress', onRelationBtnPress)
  return (
    <View style={styles.topfilter}>
      {map(sortList, (item, index) => {
        const selected = sortBy === SortTypeEnum[item.key];
        console.log('xiong  看看这是啥 selected', selected)  // false
        const asc = sortDirection === DirectionTypeEnum.asc;
        console.log('xiong  看看这是啥 asc', asc)   // false
        const color = selected ? getColors().base_oc_25 : getColors().base_oc_7;
        return (
          <TouchableOpacity
            key={index}
            style={{
              flex: 1,
              alignSelf: 'stretch',
              justifyContent: 'center',
              alignItems: 'stretch',
              // flexDirection: 'column',
              // paddingHorizontal: scaleSizeW(20),

            }}
            onPress={() => {
              const directtion = selected
                ? sortDirection === DirectionTypeEnum.desc
                  ? DirectionTypeEnum.asc
                  : DirectionTypeEnum.desc
                : sortDirection;
              onSorterPress &&
                onSorterPress(SortTypeEnum[item.key], directtion);
            }}
          >
            <View style={styles.filtersplit}>
              <Text
                style={{
                  color,
                  fontSize: scaleSizeFont(15),
                }}
              >
                {item.name}
              </Text>

              <View style={{ marginLeft: 5 }}>
                <Image
                  source={selected && asc ? ic_down_a : ic_down_n}
                  style={{
                    transform: [{ rotate: '180deg' }],
                    marginBottom: 2,
                  }}
                />
                <Image source={selected && !asc ? ic_down_a : ic_down_n} />
              </View>
            </View>
          </TouchableOpacity>
        );
      })}
      <View>
        {/* xiong  第一种 */}
        <FilterBtn
          showRelationPanel={showRelationPanel}
          selectedRelationType={selectedRelationType}
          onRelationBtnPress={onRelationBtnPress}

        // onRelationBtnPress={() => {
        //   console.log('222-222-222>>>>', showRelationPanel)
        //   this.setState({ showRelationPanel: !this.state.showRelationPanel });


        //   // console.log('222-222-222>>>>');
        // }}
        />

        {/* xiong  第二种 */}
        {/* <FilterButtons
          name={get(SorterList, [filterIndex, 'name'], '')}
          onChange={onFilterPress}
        /> */}
      </View>

      {/* <FilterPanel
        visible={showRelationPanel}
        selectedRelationType={selectedRelationType}
        // onClose={() =>
        //   this.setState({ showRelationPanel: !showRelationPanel })
        // }
        // onRelationTypeSelect={(type) =>
        //   this.setState({
        //     selectedRelationType: type,
        //     showRelationPanel: !showRelationPanel,
        //   })
        // }
        onRelationTypeSelect={onRelationTypeSelect}
      /> */}

    </View >

  );
};


const FilterBtn = (props) => {
  const { showRelationPanel, onRelationBtnPress, selectedRelationType } = props;
  // console.log('打印打印11-312312》》》》', showRelationPanel, selectedRelationType, onRelationBtnPress,)
  const source = showRelationPanel ? ic_down_a : ic_down_n;
  const color = showRelationPanel ? getColors().base_oc_25 : getColors().base_oc_7;
  const textStyle = showRelationPanel ? { color: getColors.base_fc_2 } : {};
  const imgStyle = showRelationPanel
    ? { transform: [{ rotate: '180deg' }] }
    : {};

  return (
    <TouchableOpacity style={styles.filterBtns} onPress={onRelationBtnPress} >

      <Text style={[styles.filterTexts, textStyle], {

        color: color
      }}>
        {
          selectedRelationType == 'default' ? '更多' : RelationTypeName[selectedRelationType]
        }
      </Text>
      <Image style={[styles.filterImgs, imgStyle, { marginLeft: 5 }]} source={source} />
    </TouchableOpacity>
  );
}
function CustomerStats1(props) {
  const { customerCount, assertTotal, showCustomerStats } = props;
  if (customerCount === undefined || !showCustomerStats) {
    return null;
  }

  return (
    <View
      style={{
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: getColors().base_oc_11,
        height: scaleSizeH(74),
      }}
    >
      <View style={{ flex: 1, alignItems: 'center' }}>
        <Text style={{ fontSize: 13, color: getColors().base_fc_5 }}>客户</Text>
        <Text style={{ fontSize: 17, color: getColors().base_fc_5 }}>
          {customerCount}
        </Text>
      </View>
      <View style={{ flex: 1, alignItems: 'center' }}>
        <Text style={{ fontSize: 13, color: getColors().base_fc_5 }}>
          总托管资产
        </Text>
        <Text style={{ fontSize: 17, color: getColors().base_fc_5 }}>
          {assertTotal}
        </Text>
      </View>
    </View>
  );
}

const anima = {
  duration: 80, //持续时间
  // create: {
  //   type: LayoutAnimation.Types.spring,
  //   property: LayoutAnimation.Properties.scaleXY,
  // },
  update: {
    type: LayoutAnimation.Types.linear,
    property: LayoutAnimation.Properties.scaleXY,
  },
};

// 客户统计
class CustomerStats extends PureComponent {
  constructor(props) {
    super(props);
    this.state = { marginTop: 0 };
  }

  // 向上滑动  就是让这个移动到上面去不让这个显示 -74H
  slideUp = () => {
    let { marginTop } = this.state;
    if (marginTop === 0) {
      LayoutAnimation.configureNext(anima);
      this.setState({
        marginTop: marginTop - scaleSizeH(74),
      });
    }
  };

  // 向下滑动
  slideDown() {
    let { marginTop } = this.state;
    if (marginTop < 0) {
      LayoutAnimation.configureNext(anima);
      this.setState({
        marginTop: marginTop + scaleSizeH(74),
      });
    }
  }

  render() {
    const { marginTop } = this.state;
    const { customerCount, assertTotal } = this.props;
    if (customerCount === undefined) {
      return null;
    }

    return (
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
          backgroundColor: getColors().base_oc_11,
          height: scaleSizeH(74),
          marginTop,
        }}
      >
        <View style={{ flex: 1, alignItems: 'center' }}>
          <Text style={{ fontSize: 13, color: getColors().base_fc_5 }}>
            客户
          </Text>
          <Text style={{ fontSize: 17, color: getColors().base_fc_5 }}>
            {customerCount}
          </Text>
        </View>
        <View style={{ flex: 1, alignItems: 'center' }}>
          <Text style={{ fontSize: 13, color: getColors().base_fc_5 }}>
            总托管资产
          </Text>
          <Text style={{ fontSize: 17, color: getColors().base_fc_5 }}>
            {assertTotal}
          </Text>
        </View>
      </View>
    );
  }
}
const CustomerItem = props => {
  let { goDetail, data, toggleErrorInfo, renderAlert, selectedRelationType } = props;
  console.log('看看 data是啥东西 ', data);
  const riskLevel = data.riskLevel;
  const relationType = data.relationType;
  const customerLevel = data.customerLevel;
  const isActive = data.isActive;
  console.log('我靠！！！', relationType, customerLevel, isActive);
  let name = get(data, 'name', '');
  if (name.length > 12) {
    name = name.slice(0, 11) + '...';
  }

  function _renderItemWithTips(name, value, aaa, index) {
    const commissionText = '客户本年A股普通交易佣金及本年平均佣金率';
    const turnoverRateText = '本年1月1日至今客户的资产周转率';
    console.log('看看这个传过来的是啥', aaa);
    if (aaa == 'default' || aaa == 'turnoverRate') {
      if (name && name == '月佣金') {
        console.log('走进来了妈')
        return null
      } else if (name && name == '季佣金') {
        return null
      }
    } else if (aaa == 'myjby') {
      if (name && name == '周转率') {
        return null
      } else if (name && name == '季佣金') {
        return null
      }
    } else {
      if (name && name == '周转率') {
        return null
      } else if (name && name == '月佣金') {
        return null
      }
    }

    if (name && name === '佣金') {
      return (
        <View
          // key={index}
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            width: index % 2 === 0 ? scaleSizeW(144) : scaleSizeW(159),
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: scaleSizeH(10),
              width: index % 2 === 0 ? scaleSizeW(144) : scaleSizeW(159),

            }}

          >
            <TouchableOpacity onPress={() => renderAlert && renderAlert('佣金', commissionText)} style={{
              flexDirection: 'row',

            }}>
              <Text
                style={{
                  fontSize: scaleSizeFont(15),
                  color: getColors().base_fc_5,
                  marginRight: 2,

                }}
              >
                {name}
              </Text>
              <Image
                source={ic_tips}
                style={{
                  height: scaleSizeW(15),
                  resizeMode: 'contain',
                }}
              />
            </TouchableOpacity>
            <Text
              style={{
                fontSize: scaleSizeFont(15),
                color: getColors().base_fc_5,
              }}
            >
              {value}
            </Text>
          </View>
        </View>
      );
    }
    else if (name && name === '周转率') {
      return (
        <View
          // key={index}
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            width: index % 2 === 0 ? scaleSizeW(144) : scaleSizeW(159),
          }}
        >
          <View
            style={{
              flexDirection: 'row',
              justifyContent: 'space-between',
              alignItems: 'center',
              marginBottom: scaleSizeH(10),
              width: scaleSizeW(160)
            }}
          >
            <TouchableOpacity onPress={() => renderAlert && renderAlert('周转率', turnoverRateText)} style={{
              flexDirection: 'row',

            }}>
              <Text
                style={{
                  fontSize: scaleSizeFont(15),
                  color: getColors().base_fc_5,
                  marginRight: 2,

                }}
              >
                {name}
              </Text>
              <Image
                source={ic_tips}
                style={{
                  height: scaleSizeW(15),
                  resizeMode: 'contain',
                }}
              />
            </TouchableOpacity>
            <Text
              style={{
                fontSize: scaleSizeFont(15),
                color: getColors().base_fc_5,
              }}
            >
              {value}
            </Text>
          </View>
        </View>
      );
    }
    else {
      return (
        <View
          // key={index}
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            width: scaleSizeW(159),
          }}
        >
          <View style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: scaleSizeH(10),
            width: scaleSizeW(159),
          }}>
            <Text
              style={{
                fontSize: scaleSizeFont(15),
                color: getColors().base_fc_5,
              }}
            >
              {name}
            </Text>
            <Text
              style={{
                fontSize: scaleSizeFont(15),
                color: getColors().base_fc_5,
              }}
            >

              {value}
            </Text>
          </View>
        </View>

      );
    }

  }
  return (
    <TouchableOpacity
      style={{
        alignItems: 'stretch',
        borderRadius: scaleSizeH(4),
        marginHorizontal: scaleSizeH(8),
        paddingHorizontal: scaleSizeW(12),
        backgroundColor: getColors().base_oc_11,
      }}
      onPress={() => goDetail && goDetail(data)}
    >
      <View
        style={{
          alignSelf: 'stretch',
          marginVertical: scaleSizeH(17),
        }}
      >
        <View
          style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}
        >
          <Text
            style={{
              fontSize: scaleSizeFont(19),
              color: getColors().base_fc_5,
            }}
          >
            {name}
          </Text>
          <Text
            style={{
              marginLeft: scaleSizeW(8),
              marginRight: scaleSizeW(4),
              fontSize: scaleSizeFont(13),
              color: getColors().base_fc_6,
            }}
          >
            {data.customerId}

          </Text>
        </View>
        <View style={{ flexDirection: 'row', marginTop: scaleSizeH(8) }}>
          {!!relationType && (
            <View style={styles.customerItemLabel}>
              <Text style={styles.customerItemLabelText}>{relationType}</Text>
            </View>
          )}
          {!!riskLevel && (
            <View style={styles.customerItemLabel}>
              <Text style={styles.customerItemLabelText}>{riskLevel}</Text>
            </View>
          )}
          {!!customerLevel && (
            <View style={styles.customerItemLabel}>
              <Text style={styles.customerItemLabelText}>{customerLevel}</Text>
            </View>
          )}
          {!!isActive && (
            <View
              style={
                isActive === '已激活'
                  ? styles.customerItemLabel
                  : styles.customerItemLabelGray
              }
            >
              <Text
                style={
                  isActive === '已激活'
                    ? styles.customerItemLabelText
                    : styles.customerItemLabelTextGray
                }
              >
                {isActive}
                {/* {'00000000'} */}
              </Text>
            </View>
          )}
        </View>
      </View>

      <View
        style={{
          flexWrap: 'wrap',
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'flex-start',
          borderBottomColor: getColors().base_lc_1,
        }}
      >
        {map(data.nameValue, (item, index) => {
          return item.name && _renderItemWithTips(item.name, item.value, selectedRelationType, index) || null
        }

        )}
      </View>
      <View
        style={{
          height: 1,
          marginTop: scaleSizeH(7),
          backgroundColor: getColors().base_lc_1,
        }}
      />
      <View
        style={{
          alignSelf: 'stretch',
          height: scaleSizeH(44),
          flexDirection: 'row',
          justifyContent: 'space-between',
          alignItems: 'center',
        }}
      >
        <TouchableOpacity
          style={[styles.customerItemContactView, { marginLeft: 0 }]}
          onPress={props.onFavor}
        >
          <Image
            source={data.isStore === FavorEnum.TRUE ? ic_follow_a : ic_follow_n}
            style={styles.customerItemContactImg}
          />
          <Text style={styles.customerItemContactText}>
            {data.isStore === FavorEnum.TRUE ? '取消关注' : '关注'}
          </Text>
        </TouchableOpacity>
        <View
          style={{
            alignSelf: 'stretch',
            flexDirection: 'row',
            alignItems: 'center',
          }}
        >
          {!!data.imId && (
            <TouchableOpacity
              style={styles.customerItemContactView}
              onPress={RNJumpUtils.jumpToImPage.bind(null, data.imId)}
            >
              <Image
                source={ic_message}
                style={styles.customerItemContactImg}
              />
              <Text style={styles.customerItemContactText}>消息</Text>
            </TouchableOpacity>
          )}
          <TouchableOpacity
            style={styles.customerItemContactView}
            onPress={() => {
              LinkingUtils.sendMessage(data.phone, err => {
                toggleErrorInfo &&
                  toggleErrorInfo({ visible: true, text: err });
              });
            }}
          >
            <Image
              source={ic_short_message}
              style={styles.customerItemContactImg}
            />
            <Text style={styles.customerItemContactText}>短信</Text>
          </TouchableOpacity>
          <TouchableOpacity
            style={styles.customerItemContactView}
            onPress={() => {
              LinkingUtils.makeACall(data.phone, err => {
                toggleErrorInfo &&
                  toggleErrorInfo({ visible: true, text: err });
              });
            }}
          >
            <Image
              source={ic_telephone}
              style={styles.customerItemContactImg}
            />
            <Text style={styles.customerItemContactText}>电话</Text>
          </TouchableOpacity>
        </View>
      </View>
    </TouchableOpacity>
  );
};

class AnimatedFilter extends PureComponent {
  static propTypes = {
    params: PropTypes.object.isRequired,
    onSearchPress: PropTypes.func.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      xPosition: new Animated.Value(scaleSizeW(-285)),
      ...props.params,
    };

    this._scrollView = null;
    this._scrollContentOffsetY = 0;

    this._customerLevelTypes = [
      {
        value: '1',
        name: '一级',
      },
      {
        value: '2',
        name: '二级',
      },
      {
        value: '3',
        name: '三级',
      },
      {
        value: '4',
        name: '四级',
      },
      {
        value: '5',
        name: '五级',
      },
      {
        value: 'none',
        name: '',
      },
    ];

    this._customerFavorTypes = [
      {
        value: '1',
        name: '关注',
      },
      {
        value: '0',
        name: '未关注',
      },
      {
        value: 'none',
        name: '',
      },
    ];

    this._customerRiskRatingTypes = [
      {
        value: '5',
        name: '激进型',
      },
      {
        value: '4',
        name: '积极型',
      },
      {
        value: '3',
        name: '稳健型',
      },
      {
        value: '2',
        name: '谨慎型',
      },
      {
        value: '1',
        name: '保守型',
      },
      {
        value: '0',
        name: '最低',
      },
    ];

    this._customerRelationTypes = [
      {
        value: '10',
        name: '开发',
      },
      {
        value: '1',
        name: '服务',
      },
      {
        value: '2',
        name: '签约',
      },
    ];

    this._customerAssetRangeTypes = [
      {
        name: '总资产',
        key: 'total',
      },
      {
        name: '股票资产',
        key: 'stock',
      },
      // {
      //   name: '基金资产',
      //   key: 'fund',
      // },
      // {
      //   name: '两融资产',
      //   key: 'margin',
      // },
      // {
      //   name: '可用资产',
      //   key: 'marketValueTotal',
      // },
    ];

    this._isActiveTypes = [
      {
        value: '1',
        name: '已激活',
      },
      {
        value: '0',
        name: '未激活',
      },
      {
        value: 'none',
        name: '',
      },
    ];
  }

  componentDidMount() {
    Animated.timing(this.state.xPosition, {
      toValue: 0,
      duration: 300,
    }).start();
  }

  // 资产区间输入改变回调
  _onAssetRangeTextChange = (key, range, value) => {
    let newValue = value.replace(/[^(\d)]/g, '');
    newValue = newValue.replace(/^0\d+/, '0');
    this.setState(preState => ({
      [key]: { ...preState[key], [range]: newValue },
    }));
  };

  // 渲染资产区间输入框
  _renderAssetRangeItemInputView = (key, holder, value, range) => (
    <View style={styles.scopeContainer}>
      <TextInput
        placeholder={holder}
        keyboardType="numeric"
        style={styles.scopeInputStyle}
        value={value}
        onChangeText={this._onAssetRangeTextChange.bind(null, key, range)}
      />
    </View>
  );

  // 渲染资产区间元素
  _renderAssetRangeItem = item => {
    const { name, key } = item;
    const { min, max } = this.state[key];

    return (
      <View
        key={key}
        flexDirection="row"
        style={{ marginBottom: scaleSizeH(10), alignItems: 'center' }}
      >
        <Text
          style={{
            width: scaleSizeW(72),
            fontSize: scaleSizeFont(15),
            color: getColors().base_fc_6,
          }}
        >
          {name}
        </Text>
        {this._renderAssetRangeItemInputView(key, '最低价', min, 'min')}
        <View
          style={{
            width: scaleSizeW(9),
            height: scaleSizeH(1),
            backgroundColor: getColors().base_oc_7,
            marginHorizontal: scaleSizeW(8),
          }}
        />
        {this._renderAssetRangeItemInputView(key, '最高价', max, 'max')}
      </View>
    );
  };

  // 渲染资产区间
  _renderCustomerAssetRangeTypes = () => [
    <Text key="Text" style={styles.filterTypeText}>
      资产区间
    </Text>,
    map(this._customerAssetRangeTypes, item =>
      this._renderAssetRangeItem(item)
    ),
  ];

  // 渲染每行3个元素
  _renderThreeItemsPerRow = (key, title, list) => [
    <Text key="Text" style={styles.filterTypeText}>
      {title}
    </Text>,
    <View key="View" style={styles.filterTypeView}>
      {map(list, item => {
        return item.value !== 'none' ? (
          <SelectItem
            style={{
              width: scaleSizeW(77),
              marginBottom: scaleSizeH(10),
            }}
            key={item.value}
            id={item.value}
            activeId={this.state[key]}
            onPress={() => {
              let value = item.value;
              if (this.state[key] === item.value) {
                value = undefined;
              }
              this.setState({
                [key]: value,
              });
            }}
          >
            {item.name}
          </SelectItem>
        ) : (
            <View key={item.value} style={{ width: scaleSizeW(77) }} />
          );
      })}
    </View>,
  ];

  // 渲染客户等级
  _renderCustomerLevelTypes = () =>
    this._renderThreeItemsPerRow(
      'customerLevel',
      '客户等级',
      this._customerLevelTypes
    );

  // 渲染是否关注
  _renderCustomerFavorTypes = () =>
    this._renderThreeItemsPerRow(
      'isStore',
      '是否关注',
      this._customerFavorTypes
    );

  // 渲染风险等级
  _renderCustomerRiskRatingTypes = () =>
    this._renderThreeItemsPerRow(
      'riskLevel',
      '风险等级',
      this._customerRiskRatingTypes
    );

  // 渲染客户关系
  _renderCustomerRelationTypes = () =>
    this._renderThreeItemsPerRow(
      'relationType',
      '客户关系',
      this._customerRelationTypes
    );

  // 渲染炼金术是否激活
  _renderIsActiveTypes = () =>
    this._renderThreeItemsPerRow(
      'isActive',
      '炼金术激活情况',
      this._isActiveTypes
    );

  _renderButton = (text, style, textStyle, onPress) => (
    <TouchableOpacity style={[styles.filterBtn, style]} onPress={onPress}>
      <Text style={{ fontSize: 17, ...textStyle }}>{text}</Text>
    </TouchableOpacity>
  );

  _renderButtons = () => {
    let { onCloseHandler, onSearchPress } = this.props;

    return (
      <View
        style={{
          flexDirection: 'row',
          height: scaleSizeH(50),
          borderTopColor: getColors().base_lc_1,
        }}
      >
        {this._renderButton(
          '重置',
          { backgroundColor: getColors().base_oc_28 },
          { color: getColors().base_fc_5 },
          () => this.setState(defaultFilterParams)
        )}
        {this._renderButton(
          '搜索',
          { backgroundColor: getColors().base_oc_27 },
          { color: getColors().base_fc_8 },
          () => {
            onCloseHandler && onCloseHandler();
            let params = { ...this.state };
            delete params.xPosition;
            onSearchPress && onSearchPress(params);
          }
        )}
      </View>
    );
  };

  render() {
    let { onCloseHandler } = this.props;
    let { xPosition } = this.state;

    return (
      <View
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          flexDirection: 'row',
        }}
      >
        <TouchableOpacity
          style={{
            flex: 1,
            alignSelf: 'stretch',
          }}
          onPress={() => {
            onCloseHandler && onCloseHandler();
          }}
        />
        <Animated.View
          style={{
            width: scaleSizeW(285),
            position: 'absolute',
            backgroundColor: getColors().base_oc_18,
            top: 0,
            bottom: 0,
            right: xPosition,
          }}
        >
          <ScrollView
            ref={ref => {
              this._scrollView = ref;
            }}
          >
            {Platform.OS === 'ios' ? (
              <SafeView type="top" />
            ) : (
                <View style={{ height: StatusBar.currentHeight }} />
              )}
            <View
              style={{
                paddingHorizontal: scaleSizeW(16),
                paddingBottom: scaleSizeH(40),
              }}
            >
              {this._renderCustomerAssetRangeTypes()}
              {this._renderCustomerLevelTypes()}
              {this._renderCustomerFavorTypes()}
              {this._renderCustomerRiskRatingTypes()}
              {this._renderCustomerRelationTypes()}
              {this._renderIsActiveTypes()}
            </View>
          </ScrollView>
          {this._renderButtons()}
          {Platform.OS === 'ios' ? <SafeView type="bottom" /> : null}
        </Animated.View>
      </View>
    );
  }
}

class CustomerList extends PureComponent {
  static propTypes = {
    flatListRef: PropTypes.func,
    data: PropTypes.array.isRequired,
    refresh: PropTypes.func.isRequired,
    moredata: PropTypes.func.isRequired,
    navigate: PropTypes.func.isRequired,
    refreshing: PropTypes.bool.isRequired,
    toggleErrorInfo: PropTypes.func,
    selectedRelationType: PropTypes.string,
  };

  constructor(props) {
    super(props);
    this._startDragOffsetY = null;
    this._endDragOffsetY = null;
    this._draging = false;
    this.state = {
      extraData: false,
    };
  }

  // 上拉加载时   先清楚数据 在调
  _onPullUpToEnd = () => {
    console.log('pull up!!!');
    this._clearPullUpInfo();
    this.props.moredata();
  };

  // 判断是否上拉
  _isPullUpToEnd = () =>
    this._endReached &&
    this._startDragOffsetY !== null &&
    this._endDragOffsetY !== null &&
    this._startDragOffsetY < this._endDragOffsetY;

  // 清除上拉信息
  _clearPullUpInfo = () => {
    this._startDragOffsetY = null;
    this._endDragOffsetY = null;
    this._endReached = false;
  };

  // 避免初次载入列表时，重复加载数据的BUG
  // 避免iOS下拉刷新误触发上拉加载
  // 上拉，自然滚动到底部，先触发_onScrollEndDrag，后触发_onEndReached
  _onEndReached = () => {
    this._endReached = true;
    this.setState(preState => ({ extraData: !preState.extraData }));

    // 如果是上拉，则清除上拉信息，同时触发翻页逻辑
    this._isPullUpToEnd() && this._onPullUpToEnd();
  };

  // 滑动手势开始
  // 上拉开始时，应该先做一次清除操作
  _onScrollStartDrag = e => {
    // console.log('和_onScrll 哪个会先触发  一滑动就会最先执行这个1111 ');
    const { onDraging } = this.props;
    onDraging && onDraging(e);
    this._draging = true;
    this._clearPullUpInfo();
    this._startDragOffsetY = get(e, ['nativeEvent', 'contentOffset', 'y'], 0);
    // console.log('onScrollStartDrag: ', e.nativeEvent.contentOffset);
  };

  // 滑动手势结束
  // 已经到达底部的时候，再拉的话，先触发的_onEndReached，后触发_onScrollEndDrag
  _onScrollEndDrag = e => {
    this._draging = false;
    this._endDragOffsetY = get(e, ['nativeEvent', 'contentOffset', 'y'], 0);
    console.log('onScrollEndDrag: ', e.nativeEvent.contentOffset);

    // 如果是上拉，则清除上拉信息，同时触发翻页逻辑
    this._isPullUpToEnd() && this._onPullUpToEnd();
  };
  // 滚动时触发，会触发多次
  _onScroll = e => {
    // console.log('onScroll: ', e.nativeEvent.contentOffset);
    if (this._draging) {
      // console.log('这里进了么？？？？ ', this._draging);
      const { onDraging } = this.props;
      onDraging && onDraging(e);
    }
  };

  _onRefresh = () => {
    this.props.refresh();
  };

  // 跳转到 客户全景
  _goDetail = item => {
    let { navigate, appVersion } = this.props;
    if (!!appVersion) {
      // 有版本号代表的是新版本，新版本App跳转到原生的客户全景
      RNJumpUtils.jumpToCustomerDetail(item.customerId);
    } else {
      // 老版本跳转到自带的客户全景
      navigate('CustomerDetail', { customerId: item.customerId });
    }
  };

  _keyExtractor = (item, index) => index.toString();

  _renderItem = ({ item, index }) => (
    <CustomerItem
      key={index}
      data={item}
      goDetail={this._goDetail}
      onFavor={this.props.onFavor.bind(null, item, index)}
      toggleErrorInfo={this.props.toggleErrorInfo}
      renderAlert={this._renderAlert}
      selectedRelationType={this.props.selectedRelationType}
    />
  );

  _renderItemSeparatorComponent() {
    return <View style={{ height: 8 }} />;
  }

  // 佣金率提示信息
  _renderAlert = (title, content) => {
    this.props.toggleOverlayContainer({
      visible: true,
      componentCreator: onCloseHandler => {
        return (
          <View
            style={{
              flex: 1,
              justifyContent: 'center',
              alignItems: 'center',
            }}
          >
            <DialogAlert
              title={title}
              content={content}
              type={'single'}
              firstBtnTitle={'确定'}
              onFirstBtnPress={() => {
                onCloseHandler && onCloseHandler();
              }}
            />
          </View>
        );
      },
    });
  };

  render() {
    return (
      <View
        style={{
          backgroundColor: getColors().base_oc_10,
          flex: 1,
          alignSelf: 'stretch',
          paddingTop: 8,
        }}
      >
        {/* 每一个小块的内容 */}
        <FlatList
          ref={ref => {
            this.props.flatListRef && this.props.flatListRef(ref);
          }}
          data={this.props.data}
          extraData={this.state.extraData}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
          ItemSeparatorComponent={this._renderItemSeparatorComponent}
          refreshing={this.props.refreshing}
          onEndReachedThreshold={0.0001}
          onEndReached={this._onEndReached}
          onScrollBeginDrag={this._onScrollStartDrag}
          onScrollEndDrag={this._onScrollEndDrag}
          onScroll={this._onScroll}
          onRefresh={this._onRefresh}
          selectedRelationType={this.props.selectedRelationType}
        />
      </View>
    );
  }
}

class CustomerContainer extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      assertTotal: undefined,
      customerCount: undefined,
      list: [],
      sortBy: SortTypeEnum.default,
      sortDirection: DirectionTypeEnum.desc,
      refreshing: false,
      search: '',
      showSearchView: false,
      showCustomerStats: true,

      //  xiong
      showRelationPanel: false, // 关系选择面板
      // selectedRelationType: RelationType.weeks,
      selectedRelationType: 'default',

      // xiong 第二种
      selectorIndex: 0,
      showFilterList: false,
    };

    this._showTips = false;
    this._flatListRef = null;
    this._sleep = false;
    this._pageSize = 10;
    this._filterParams = defaultFilterParams;
    this._searchText = '';
    this._index = 0;
    this._sortList = [
      {
        key: 'total',
        name: '总资产',
      },
      {
        key: 'availableTotal',
        name: '可用资产',
      },
      // {
      //   key: 'turnoverRate',
      //   name: '周转率',
      // },
      {
        key: 'operDate',
        name: '开户时间',
      },
      // {
      //   key: 'moreandMore' ,
      //   name: '更多'
      // }
    ];
  }

  componentWillMount() {
    let { getParam, navigate } = this.props.navigation;
    let page = getParam('page');
    let data = getParam('data');

    // 如果外部直接跳转到指定的page页，page页必须去后端请求数据，而不是接收路由跳转时携带的数据
    if (page) {
      navigate(page, {
        needLoadData: true,
        customerId: data.customerId,
      });
    }
  }

  componentDidMount() {
    // 如果是路由首页，则需要在此让过渡动画消失
    const key = get(this, ['props', 'navigation', 'state', 'key'], 'key');
    const routeName = get(
      this,
      ['props', 'navigation', 'state', 'routeName'],
      'routeName'
    );
    key === routeName && LoadingProgramModule.hide();

    this._fetchCustomersOverview();
    this._loadData();
  }

  _fetchCustomersOverview = () => {
    let { fetchData } = this.props;

    const data = {};
    fetchData({
      path: api.customersOverview,
      method: 'post',
      body: {
        data,
      },
      callback: res => {
        const assertTotal = get(res, 'assetTotal', '');
        const customerCount = get(res, 'customerCount', 0) + '人';

        this.setState({
          assertTotal,
          customerCount,
        });
      },
      errCallback: err => { },
    });
  };

  // 创建参数
  _createParams = (index, sortBy, sortDirection, search, filterParams) => {
    console.log('看看参数index', index)  // 0
    console.log('看看参数sortBy', sortBy)  //  DEFAULT   上面几个类型 总资产 可用资长 。。。  默认是第一个 DEFAULT 
    console.log('看看参数sortDirection', sortDirection)  // DESC   箭头朝上朝下  DESC下  ASC上
    console.log('看看参数search', search)  // kong
    console.log('看看参数filterParams', filterParams)   // 

    const { _pageSize } = this;

    // 组CustomerFilterAsset
    const asset = {};
    !VerifyDataUtils.isEmptyValue(filterParams.total) &&
      (asset.total = { ...filterParams.total });
    !VerifyDataUtils.isEmptyValue(filterParams.stock) &&
      (asset.stock = { ...filterParams.stock });
    !VerifyDataUtils.isEmptyValue(filterParams.fund) &&
      (asset.fund = { ...filterParams.fund });
    !VerifyDataUtils.isEmptyValue(filterParams.margin) &&
      (asset.margin = { ...filterParams.margin });
    !VerifyDataUtils.isEmptyValue(filterParams.marketValueTotal) &&
      (asset.marketValueTotal = { ...filterParams.marketValueTotal });
    for (let key in asset) {
      let value = asset[key];
      value.min = value.min && toNumber(value.min);
      value.max = value.max && toNumber(value.max);
    }
    console.log('asset是什么东西？', asset)
    // 组CustomerFilter
    let params = {};
    !VerifyDataUtils.isEmptyValue(asset) && (params.asset = asset);
    filterParams.customerLevel &&
      (params.customerLevel = filterParams.customerLevel);
    filterParams.isStore && (params.isStore = filterParams.isStore);
    filterParams.relationType &&
      (params.relationType = filterParams.relationType);
    filterParams.riskLevel && (params.riskLevel = filterParams.riskLevel);
    filterParams.isActive && (params.isActive = filterParams.isActive);
    search && (params.search = search);
    console.log('999999999---99999999', params)

    const data = {
      index,
      sortBy,
      sortDirection,
      pageSize: _pageSize,
    };
    console.log('data是什么东西？', data)

    // 决定是否显示tips
    if (VerifyDataUtils.isEmptyValue(params)) {
      this._showTips = false;
    } else {
      data.filter = params;
      this._showTips = true;
    }

    return data;
  };

  // 从服务器请求数据   五个参数   
  _fetchCustomerList = (
    sortBy,
    sortDirection,
    search,
    filterParams,
    requestType = RequestTypes.load
  ) => {
    // 避免多次重复请求
    if (this._sleep) return;
    this._sleep = true;

    let index = 0;
    if (requestType === RequestTypes.refresh) {
      this.setState({
        refreshing: true,
      });
    } else if (requestType === RequestTypes.page) {
      index = this._index + 1;
    }

    const data = this._createParams(
      index,
      sortBy,
      sortDirection,
      search,
      filterParams
    );
    console.log('你好data我要看看你 里面 有啥东西！！！', data);
    let { fetchData } = this.props;
    fetchData({
      path: api.customersList,
      method: 'post',
      body: {
        data,
      },
      showLoading: !(requestType === RequestTypes.refresh),
      callback: res => {
        // 保存筛选条件和搜索词
        this._searchText = search;
        this._filterParams = { ...filterParams };

        const items = get(res, 'items', []);
        const length = get(items, 'length', 0);

        // 处理列表，获取的列表不为空，页码才更新
        if (length !== 0) {
          this._index = index;
        }

        const newState = Object.create(null);
        let { list } = this.state;
        console.log('list组件看看有啥', items);

        if (requestType === RequestTypes.refresh) {
          list = [...items];
          newState.refreshing = false;
        } else if (requestType === RequestTypes.page) {
          list = [...list, ...items];
        } else {
          list = [...items];
        }
        newState.list = list;
        newState.search = search;
        newState.sortBy = sortBy;
        newState.sortDirection = sortDirection;
        newState.showSearchView = false;
        // 到时候要在这里加 type  选择框
        console.log('这个是啥来着我来瞅瞅!', newState);
        this.setState(newState, () => {
          // 取第一页场景应该滚动到第一条
          requestType === RequestTypes.load &&
            this._flatListRef.scrollToOffset({ animated: false, offset: 0 });
          // state设置成功后才将锁定状态解锁
          this._sleep = false;
        });
      },
      errCallback: err => {
        const { showSearchView } = this.state;
        const newState = Object.create(null);
        showSearchView && (newState.showSearchView = false);
        requestType === RequestTypes.refresh && (newState.refreshing = false);
        search !== this._searchText && (newState.search = this._searchText);

        // 待更新的数据不为空才刷新页面
        if (Object.keys(newState).length !== 0) {
          this.setState(newState, () => (this._sleep = false));
        } else {
          this._sleep = false;
        }
      },
    });
  };
  // componentDidMount
  // 页面载入初次加载数据
  _loadData = () => {
    // 记得在这里加参数  ！！！！把默认的 RelationType.weeks 也传过去
    this._fetchCustomerList(
      SortTypeEnum.default,  // 默认   DEFAULT
      DirectionTypeEnum.desc,   // DESC
      '',
      defaultFilterParams,
      RequestTypes.load  // 获取第一页的意思
    );
  };

  // 处理上拉加载 
  _moreData = () => {
    const { search, sortBy, sortDirection } = this.state;
    const { _filterParams } = this;
    // console.log('这里是上拉加载？？？ 是的');
    this._fetchCustomerList(
      sortBy,
      sortDirection,
      search,
      _filterParams,
      RequestTypes.page
    );
  };

  // 处理下拉刷新
  _refreshData = () => {
    const { search, sortBy, sortDirection } = this.state;
    const { _filterParams } = this;
    // console.log('这里是下拉刷新？？？  是的');
    this._fetchCustomerList(
      sortBy,
      sortDirection,
      search,
      _filterParams,
      RequestTypes.refresh
    );
  };

  //
  // 处理排序
  _handleSort = (sortBy, sortDirection) => {
    console.log('xiong 点击上面会触发啥东西', sortBy, sortDirection)  // 箭头朝下 ：TOTAL   DESC      箭头朝上 TOTAL   ASC     2: AVAILABLE_TOTAL DESC   AVAILABLE_TOTAL ASC
    const { search } = this.state;
    const { _filterParams } = this;
    this._fetchCustomerList(
      sortBy,
      sortDirection,
      search,
      _filterParams,
      RequestTypes.load
    );
  };

  // 处理页面搜索
  _handleSearch = () => {
    const { search, sortBy, sortDirection } = this.state;
    const { _filterParams } = this;
    console.log('这里面都是啥啊啊啊啊啊？？', search, sortBy, sortDirection, _filterParams);
    this._fetchCustomerList(
      sortBy,
      sortDirection,
      search,
      _filterParams,
      RequestTypes.load
    );
  };

  // 处理筛选器的搜索
  _handleFilter = params => {
    const { search, sortBy, sortDirection } = this.state;
    this._fetchCustomerList(
      sortBy,
      sortDirection,
      search,
      params,
      RequestTypes.load
    );
  };

  // 处理筛选按钮点击事件
  _onFilterBtnPress = () => {
    {
      this.props.toggleOverlayContainer({
        visible: true,
        componentCreator: onCloseHandler => {
          return (
            <AnimatedFilter
              params={this._filterParams}
              onCloseHandler={onCloseHandler}
              onSearchPress={this._handleFilter}
            />
          );
        },
      });
    }
  };

  _onFavor = (item, index) => {
    const { isStore, customerId } = item;
    const { fetchData } = this.props;

    const isStoreNew = isStore === '0' ? '1' : '0';
    const data = {
      customerId,
      isStore: isStoreNew,
      type: 'CUSTOMER',
    };
    fetchData({
      path: api.customerCollectClick,
      method: 'post',
      body: {
        data,
      },
      callback: () => {
        const { list } = this.state;
        const targetItem = list[index];
        targetItem.isStore = isStoreNew;
        this.setState({ list: [...list] });
      },
      errCallback: err => { },
    });
  };

  _renderClear = () => {
    return this.state.search && this.state.showSearchView ? (
      <TouchableOpacity
        hitSlop={{
          top: scaleSizeH(10),
          bottom: scaleSizeH(10),
          left: scaleSizeH(10),
          right: scaleSizeH(10),
        }}
        onPress={() => this.setState({ search: '' })}
      >
        <Image
          style={{
            width: scaleSizeH(16),
            height: scaleSizeH(16),
            resizeMode: 'contain',
          }}
          source={ic_clear}
        />
      </TouchableOpacity>
    ) : null;
  };

  // 顶部搜索栏
  _renderTopSearchBar = () => (
    <View
      flexDirection="row"
      style={{
        alignSelf: 'stretch',
        height: scaleSizeH(44),
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: getColors().base_oc_11,
        paddingHorizontal: scaleSizeW(16),
        paddingVertical: scaleSizeH(7),
        zIndex: 99,
        // backgroundColor: 'red'
      }}
    >
      <TouchableOpacity
        style={{
          flex: 1,
          alignSelf: 'stretch',
          paddingHorizontal: scaleSizeW(9),
          backgroundColor: getColors().base_oc_10,
          flexDirection: 'row',
          alignItems: 'center',
        }}
        onPress={() => {
          this.refs.searchInputRef.focus();
          this.setState({ showSearchView: true });
        }}
      >
        <Image
          style={{
            width: scaleSizeW(17),
            height: scaleSizeW(17),
            resizeMode: 'contain',
          }}
          source={ic_search}
        />
        <TextInput
          ref="searchInputRef"
          placeholder="搜索"
          style={{
            flex: 1,
            alignSelf: 'stretch',
            marginLeft: scaleSizeW(8),
          }}
          onTouchStart={() => this.setState({ showSearchView: true })}
          returnKeyType="search"
          autoCorrect={false}
          onChangeText={search => this.setState({ search })}
          onSubmitEditing={e => {
            const text = e.nativeEvent.text;
            console.log('这个是搜索框输入的么？？？', text)
            if (/[^0-9|a-z|A-Z|\u4E00-\u9FA5]/.test(text)) {
              this.props.toggleErrorInfo({
                visible: true,
                text: '仅支持输入字母、数字或中文',
              });
              return;
            }

            this._handleSearch();
          }}
          value={this.state.search}
        />
        {this._renderClear()}
      </TouchableOpacity>
      <TouchableOpacity
        style={{
          alignSelf: 'stretch',
          flexDirection: 'row',
          justifyContent: 'center',
          alignItems: 'center',
          marginLeft: scaleSizeW(8),
        }}
        onPress={() => {
          if (this.state.showSearchView) {
            this.refs.searchInputRef.blur();
            this.setState({ showSearchView: false, search: this._searchText });
          } else {
            this._onFilterBtnPress();
          }
        }}
      >
        <Text
          style={{
            fontSize: scaleSizeFont(15),
            color: getColors().base_oc_7,
          }}
        >
          {this.state.showSearchView ? '取消' : '筛选'}
        </Text>
        {this.state.showSearchView ? null : (
          <Image
            source={ic_screen}
            style={{
              width: scaleSizeW(10),
              height: scaleSizeW(12),
              marginLeft: scaleSizeW(3),
            }}
          />
        )}
      </TouchableOpacity>
    </View>
  );

  // 筛选条件为空的时候 显示这里
  _renderTips = () => {
    return this._showTips && this.state.list.length === 0 ? (
      <View
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          right: 0,
          bottom: 0,
          alignItems: 'center',
          backgroundColor: getColors().base_oc_10,
        }}
      >
        <Image
          style={{
            marginTop: scaleSizeH(80),
            width: scaleSizeH(240),
            height: scaleSizeH(150),
            resizeMode: 'contain',
          }}
          source={ic_cannot_find}
        />
        <Text
          style={{
            marginTop: scaleSizeH(35),
            lineHeight: 20,
            color: getColors().base_fc_6,
            fontSize: scaleSizeFont(15),
          }}
        >
          没有找到符合条件客户
        </Text>
        <Text
          style={{
            lineHeight: 20,
            color: getColors().base_fc_6,
            fontSize: scaleSizeFont(15),
          }}
        >
          请
          <Text
            style={{ color: getColors().base_fc_2 }}
            onPress={this._loadData}
          >
            清空条件
          </Text>
          或重新选择筛选条件
        </Text>
      </View>
    ) : null;
  };

  // 滑动时 这个也会触发
  _onDraging = e => {
    const offsetY = e.nativeEvent.contentOffset.y;
    // console.log('当我拉动的时候！！ ---- 》》》 ', offsetY)
    // 兼容下拉刷新
    if (offsetY <= 0) {
      this._scrollContentOffsetY = offsetY;
      return;
    }

    if (offsetY > this._scrollContentOffsetY) {
      // console.log('这里是向上划？？？');
      this._customerStatsRef.slideUp();
    } else {
      // console.log('这里是向下划？？？');
      this._customerStatsRef.slideDown();
    }

    this._scrollContentOffsetY = offsetY;
  };

  _onScrollUp = flag => {
    // console.log('这里是向上？？？？  这里都没打印哦！！！' , flag);
    if (flag) {
      this._customerStatsRef.slideUp();
    } else {
      this._customerStatsRef.slideDown();
    }
  };

  render() {
    const {
      showRelationPanel,
      selectedRelationType,
      showCustomerStats,
      sortBy,
      sortDirection,
      list,
      refreshing,
      customerCount,
      assertTotal,
      showSearchView,
    } = this.state;
    const { navigate } = this.props.navigation;
    const { appVersion, toggleErrorInfo, toggleOverlayContainer } = this.props;

    return (
      <SafeAreaView style={styles.container}>
        {this._renderTopSearchBar()}
        <View style={styles.container}>
          <TopFilter
            sortList={this._sortList}
            sortBy={sortBy}
            showRelationPanel={showRelationPanel}
            selectedRelationType={selectedRelationType}
            sortDirection={sortDirection}
            onSorterPress={this._handleSort}

            // xiong 第一种
            onRelationBtnPress={() => {
              console.log('222-222-222>>>>', showRelationPanel)
              this.setState({ showRelationPanel: !showRelationPanel });
            }}
          />
          <FilterPanel
            visible={showRelationPanel}

            selectedRelationType={selectedRelationType}
            onClose={() =>
              this.setState({ showRelationPanel: !showRelationPanel })
            }
            onRelationTypeSelect={(type) =>

              this.setState({
                selectedRelationType: type,
                showRelationPanel: !showRelationPanel,
              }, () => {
                console.log('到时候直接在这里写 调接口就好了！！！', type)
              })
            }
          />
          {/* 客户   总托管资产  -----》》》》  客户统计 */}
          <CustomerStats
            ref={ref => {
              this._customerStatsRef = ref;
            }}
            assertTotal={assertTotal}
            customerCount={customerCount}
            showCustomerStats={showCustomerStats}
          />
          <CustomerList
            flatListRef={ref => {
              this._flatListRef = ref;
            }}
            data={list}
            onFavor={this._onFavor}
            navigate={navigate}
            refreshing={refreshing}
            refresh={this._refreshData}
            moredata={this._moreData}
            onDraging={this._onDraging}
            toggleErrorInfo={toggleErrorInfo}
            appVersion={appVersion}
            toggleOverlayContainer={toggleOverlayContainer}
            selectedRelationType={selectedRelationType}
          />
          {this._renderTips()}
          {showSearchView ? (
            <View
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: getColors().base_oc_11,
              }}
            />
          ) : null}

        </View>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    flex: 1,
    alignSelf: 'stretch',
    backgroundColor: getColors().base_oc_11,
  },
  separator: {
    width: 1,
    height: scaleSizeH(20),
    backgroundColor: getColors.base_lc_1,
  },
  topfilter: {
    height: 44,
    backgroundColor: '#FFFFFF',
    borderBottomWidth: 1,
    borderBottomColor: '#EBEBEB',
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    zIndex: 99,   // 这里给zindex 是因为点击 搜索的时候 这块也要显示才对  所以给zindex
    // justifyContent: 'space-between',
    // flex: 1,
  },
  customerItemLabel: {
    borderWidth: 1,
    borderColor: 'rgba(0, 78, 204, 0.4)',
    borderRadius: scaleSizeH(9),
    marginRight: scaleSizeW(4),
    height: scaleSizeH(18),
    justifyContent: 'center',
    paddingHorizontal: scaleSizeW(9),
  },
  customerItemLabelGray: {
    borderWidth: 1,
    borderColor: '#999999',
    borderRadius: scaleSizeH(9),
    marginRight: scaleSizeW(4),
    height: scaleSizeH(18),
    justifyContent: 'center',
    paddingHorizontal: scaleSizeW(9),
  },
  customerItemLabelText: {
    color: getColors().base_fc_2,
    fontSize: scaleSizeFont(11),
  },
  customerItemLabelTextGray: {
    color: '#999999',
    fontSize: scaleSizeFont(11),
  },
  customerItemContactView: {
    alignSelf: 'stretch',
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: scaleSizeW(20),
  },
  customerItemContactImg: {
    width: scaleSizeW(16),
    height: scaleSizeW(16),
    resizeMode: 'contain',
  },
  customerItemContactText: {
    fontSize: scaleSizeFont(13),
    color: getColors().base_fc_6,
    marginLeft: scaleSizeW(3),
  },
  filtersplit: {
    borderRightWidth: 1,
    borderRightColor: '#EBEBEB',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  filterTypeText: {
    fontSize: 17,
    fontWeight: '500',
    color: getColors().base_fc_5,
    marginTop: 17,
    marginBottom: 25,
  },
  filterTypeView: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    flexWrap: 'wrap',
    marginBottom: scaleSizeH(7),
  },
  scopeContainer: {
    width: 78,
    height: 28,
    borderRadius: 14,
    backgroundColor: getColors().base_oc_28,
    justifyContent: 'center',
    alignItems: 'center',
  },
  scopeInputStyle: {
    flex: 1,
    alignSelf: 'stretch',
    textAlign: 'center',
  },
  filterBtn: {
    flex: 1,
    alignSelf: 'stretch',
    justifyContent: 'center',
    alignItems: 'center',
  },
  footer: {
    flexDirection: 'row',
    height: 24,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 10,
  },
  // xiong
  filterBtns: {
    width: scaleSizeW(90),
    height: scaleSizeH(40),
    // marginLeft: scaleSizeW(5),
    marginRight: scaleSizeW(5),
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  filterTexts: {
    fontSize: scaleSizeFont(15),
    color: getColors.base_fc_6,
  },
  filterImgs: {
    width: scaleSizeW(6),
    height: scaleSizeW(4),
    resizeMode: 'contain',
  },
});

const mapStateToProps = state => {
  return {
    appVersion: state.common.appVersion,
  };
};

const mapDispatchToProps = dispatch => {
  return bindActionCreators(
    {
      fetchData,
      toggleErrorInfo,
      toggleOverlayContainer,
    },
    dispatch
  );
};

export default connect(mapStateToProps, mapDispatchToProps)(CustomerContainer);
